package it.avantsoft.ls.peer;

import it.avantsoft.ls.peer.message.*;
import it.avantsoft.ls.util.SimpleEntry;
import org.apache.log4j.Logger;

import java.io.DataOutputStream;
import java.io.OutputStream;

public class SenderMessageToGL {
    private static Logger log = Logger.getLogger(SenderMessageToGL.class);

    private DataOutputStream dataOutputStream;

    public SenderMessageToGL(OutputStream output) {
        dataOutputStream = new DataOutputStream(output);
    }

    private void log(PeerMessage msg) {
        log.info("send message to gl = " + msg);
    }

    public boolean welcome(int listeningPort) {
        WelcomeMessage message = new WelcomeMessage(dataOutputStream, listeningPort);
        log(message);
        return message.send();
    }

    public boolean ackNewChild(String childId, String groupLeaderHost, int groupLeaderPort) {
        AckNewChildMessage message = new AckNewChildMessage(dataOutputStream, childId, groupLeaderHost, groupLeaderPort);
        log(message);
        return message.send();
    }

    public boolean connect(String peerId, int listeningPort) {
        ConnectMessage message = new ConnectMessage(dataOutputStream, peerId, listeningPort);
        log(message);
        return message.send();
    }

    public boolean pong() {
        PingMessage message = new PingMessage(dataOutputStream);
        log(message);
        return message.send();
    }


    public boolean signalSon(String id) {
        NewSonABMessage message = new NewSonABMessage(dataOutputStream, id);
        log(message);
        return message.send();
    }

    public boolean reconnect(String peerId, String exGroupLeaderId) {
        ReconnectMessage message = new ReconnectMessage(dataOutputStream, peerId, exGroupLeaderId);
        log(message);
        return message.send();
    }

    public boolean signalHorizontalExchangeablePeer(SimpleEntry worstPeer, String designedGroupLeaderId) {
        HorizontalExchangeablePeerMessage message = new HorizontalExchangeablePeerMessage(dataOutputStream, (String) worstPeer.getKey(), designedGroupLeaderId);
        log(message);
        return message.send();
    }
}
